package com.kcyu.sfherp.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kcyu.sfherp.entity.LoginUser;
import com.kcyu.sfherp.entity.UserRecords;
import com.kcyu.sfherp.mapper.ms.UserRecordsMapper;
import com.kcyu.sfherp.service.UserRecordsService;
import com.kcyu.sfherp.utils.BodyReaderHttpServletRequestWrapper;
import com.kcyu.sfherp.utils.JwtUtil;
import com.kcyu.sfherp.utils.MyUtils;
import com.kcyu.sfherp.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;

//@Component
public class RequestContextInterceptor implements Filter {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserRecordsMapper userRecordsMapper;

    @Autowired
    private UserRecordsService userRecordsService;

    class RequestWrapper extends HttpServletRequestWrapper {
        private final String body;

        public RequestWrapper(HttpServletRequest request) {
            super(request);
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = null;
            InputStream inputStream = null;
            try {
                inputStream = request.getInputStream();
                if (inputStream != null) {
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    char[] charBuffer = new char[128];
                    int bytesRead = -1;
                    while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                        stringBuilder.append(charBuffer, 0, bytesRead);
                    }
                } else {
                    stringBuilder.append("");
                }
            } catch (IOException ex) {
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            body = stringBuilder.toString();
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
            ServletInputStream servletInputStream = new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return false;
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setReadListener(ReadListener readListener) {
                }

                @Override
                public int read() throws IOException {
                    return byteArrayInputStream.read();
                }
            };
            return servletInputStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(this.getInputStream()));
        }

        public String getBody() {
            return this.body;
        }

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        System.out.println(request);
        HttpServletRequest request1 = (HttpServletRequest) request;
        if(request1.getRequestURI().contains("swagger-ui")) {
            filterChain.doFilter(request, response);
            return;
        }

        if(request1.getRequestURI().contains("api-docs")) {
            filterChain.doFilter(request, response);
            return;
        }

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        ServletRequest requestWrapper = null;
        String body = null;


        try {
            LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (user.getUsername().equals("维护专用")) {
                filterChain.doFilter(request, response);
                return;
            }
            if (request != null) {
                requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
            }
            if (requestWrapper == null) {
                filterChain.doFilter(request, response);
            } else {
                System.out.println("------------------------------请求报文----------------------------------");
                body = getParamsFromRequestBody((HttpServletRequest) requestWrapper);
                body = MyUtils.getTransString(body);
                System.out.println(body);
                System.out.println("------------------------------请求报文----------------------------------");

            }


            String decode = URLDecoder.decode(httpServletRequest.getRequestURI(), "UTF-8");

            UserRecords records = new UserRecords();
            records.setUsername(user.getUsername());
            records.setUrl(decode);
            records.setValue(body);
            userRecordsService.addRecordImpl(records);
        } catch (Exception e) {
            filterChain.doFilter(request, response);
            return;
        }


        filterChain.doFilter(requestWrapper, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    private String getParamsFromRequestBody(HttpServletRequest request) throws IOException {
        BufferedReader br = null;
        String listString = "";
        try {
            br = request.getReader();

            String str = "";

            while ((str = br.readLine()) != null) {
                listString += str;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return listString;
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
